package com.itheima.d6_Set;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {
    public static void main(String[] args) {
        // 明白TreeSet的排序
        Set<String> sets = new TreeSet<>();
        sets.add("23");
        sets.add("Java");
        sets.add("A");
        System.out.println(sets);
        System.out.println("=========添加自定义的对象TreeSet========");
        Set<Apple> apples = new TreeSet<>();
        Apple apple1 = new Apple("红",12.4);
        Apple apple2 = new Apple("蓝",12.5);
        Apple apple3 = new Apple("紫",12.5);
        apples.add(apple1);
        apples.add(apple2);
        apples.add(apple3);
        System.out.println(apples);
        System.out.println("方式二-================");
        Set<Apple> apple = new TreeSet<>(new Comparator<Apple>() {
            @Override
            //这个方法先取两个数  7 8 9 10； 7 8 作为比较；注意的是 取出来是 8 7 这样对o1 o2
            // 负数 倒序； 正数 正常顺序
            public int compare(Apple o1, Apple o2) {
                if (o1.getPrice() > o2.getPrice()) {
                    return -1;
                } else if (o1.getPrice() < o2.getPrice()) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        Apple apple4 = new Apple("红",12.4);
        Apple apple5 = new Apple("蓝",12.5);
        Apple apple6 = new Apple("紫",12.5);
        apple.add(apple4);
        apple.add(apple5);
        apple.add(apple6);
        System.out.println(apple);
    }
}

//方式1： Apple类实现Comparable接口
class Apple implements Comparable<Apple>{
    private String name;
    private double price;

    public Apple() {
    }

    public Apple(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    /**
     * o1.compareTo(o2)
     * @param o
     * @return
     */
    @Override
    public int compareTo(Apple o) {
        if (this.price > o.price){
            return 1;
        }else if (this.price < o.price){
            return -1;
        }else {
            return 0;
        }
    }

    @Override
    public String toString() {
        return "Apple{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}